//
//  WPRewardsViewController.m
//  ZhongChouPingTai
//
//  Created by WeiPan on 16/3/31.
//  Copyright © 2016年 WPJoe. All rights reserved.
//

#import "WPRewardsViewController.h"
#import "WPNewsPreheatModel.h"
#import "WPNewsPreheatTableViewCell.h"
#import "WPNewsDealingModel.h"
#import "WPNewsDealingTableViewCell.h"
#import "WPTradeListViewController.h"
#import "WPTradeDetailViewController.h"

static NSString *const kUITableViewCellIdentifier = @"cellIdentifier";

@interface WPRewardsViewController ()<UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UISegmentedControl * segmentControl;/**< 分段控件 */
@property (nonatomic, strong) UIScrollView * backScrollView;/**< 滚动视图 */
@property (nonatomic, strong) UITableView * tradeTableView;/**< 交易表格视图 */
@property (nonatomic, strong) NSMutableArray * tradeArr;/**< 交易数据源 */
@property (nonatomic, strong) NSArray * detailImageNames;/**< 详情图片数组 */
@property (nonatomic, strong) UIView * footView;/**< 列表表尾 */
@property (nonatomic, strong) UIView * rightView;/**< 右边视图 */
@property (nonatomic, strong) UILabel * noMoreLabel;/**< 没有说明 */
@property (nonatomic, assign) CGPoint bfContentOffset;/**< 减速前的偏移量 */

- (void)initializeDataSource; /**< 初始化数据源 */
- (void)initializeUserInterface; /**< 初始化用户界面 */
- (void)refreshData;/**< 刷新数据 */


@end

@implementation WPRewardsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeUserInterface];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar addSubview:self.segmentControl];
}
- (void)viewWillDisappear:(BOOL)animated {
    [self.segmentControl removeFromSuperview];
}
#pragma mark - init
- (void)initializeDataSource {
    self.detailImageNames = @[@"rain项目详情", @"迪斯尼项目详情", @"bigbang项目详情"];
    self.tradeArr = [NSMutableArray arrayWithCapacity:0];
    WPNewsPreheatModel * model = [WPNewsPreheatModel new];
    model.image = @"image1";
    model.name = @"BIGBANG “WORLDTOUR[MADE]” 亚洲巡演";
    model.detailDescriiption = @"BIGBANG五人全体三巡首站上海.南京.深圳.北京.广州.天津.武汉.厦门.西安···入伍前全体最后一次巡演...";
    model.involvementNumber = @(41278);
    NSString * bigbangTime = @"20160616";
    NSString * disiniTime = @"20160701";
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyyMMdd";
    NSDate * date = [formatter dateFromString:bigbangTime];
    NSDate * disiniDate = [formatter dateFromString:disiniTime];
    NSTimeInterval bigBangInterval = [date timeIntervalSince1970];
    NSTimeInterval disiniInrerval = [disiniDate timeIntervalSince1970];
    model.endDate = @(bigBangInterval*1000);
    WPNewsPreheatModel * model1 = [WPNewsPreheatModel new];
    model1.image = @"image2";
    model1.name = @"上海迪斯尼乐园6月16日开园庆典";
    model1.detailDescriiption = @"作为中国大陆首座迪尼斯主题乐园，上海迪尼斯乐园将为游客提供无限可能，创造值得珍藏一生的回忆...";
    model1.involvementNumber = @(41278);
    model1.endDate = @(disiniInrerval*1000);
    
    WPNewsDealingModel * model2 = [WPNewsDealingModel new];
    model2.posterImageName = @"image3";
    model2.title = @"“The squall” Rain亚洲演唱会";
    model2.detail = @"2016“The Squall”王者归来Rain亚洲巡回演唱会-成都站。喊了那么久，终于Rain来了!迎风...";
    model2.ticketCount = @"750";
    model2.allTicketCount = @"800";
    model2.joinCount = @"200";
    model2.leftDays = @"8";
    [_tradeArr addObject:model2];
    [_tradeArr addObject:model1];
    [_tradeArr addObject:model];
}
- (void)initializeUserInterface {
    self.navigationController.navigationBarHidden = NO;
    [self.view addSubview:self.backScrollView];
    [_backScrollView addSubview:self.tradeTableView];
    [_backScrollView addSubview:self.rightView];
    __weak typeof(self)weakself = self;
    _tradeTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakself refreshData];
    }];
    _tradeTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakself refreshData];
    }];
    [_tradeTableView.header beginRefreshing];
}
#pragma mark - responds events
- (void)respondsToSegment:(UISegmentedControl *)sender {
    _tradeTableView.hidden = sender.selectedSegmentIndex;
    if (sender.selectedSegmentIndex) {
        [_backScrollView setContentOffset:CGPointMake(SCREEN_SIZE.width, 0) animated:YES];
    } else {
        [_backScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
}
#pragma mark - 刷新数据
- (void)refreshData {
    if (_tradeTableView.footer.isRefreshing) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_tradeTableView.footer noticeNoMoreData];
        });
    }
    if (_tradeTableView.header.isRefreshing) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_tradeTableView.header endRefreshing];
        });
    }

}

#pragma mark - UIScrollView Protocol
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    self.bfContentOffset = scrollView.contentOffset;
//    if (scrollView.contentOffset.x > SCREEN_SIZE.width/2) {
//        _segmentControl.selectedSegmentIndex = 1;
//        [_backScrollView setContentOffset:CGPointMake(SCREEN_SIZE.width, 0) animated:YES];
//    } else {
//        _segmentControl.selectedSegmentIndex = 0;
//        [_backScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
//    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGPoint contentOffset = scrollView.contentOffset;
    if (contentOffset.x > _bfContentOffset.x) {
        _segmentControl.selectedSegmentIndex = 1;
        [_backScrollView setContentOffset:CGPointMake(SCREEN_SIZE.width, 0) animated:YES];
    } else {
        _segmentControl.selectedSegmentIndex = 0;
        [_backScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
}
#pragma mark - 协议UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _tradeArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section != 0) {
        WPNewsPreheatTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (!cell) {
            cell = [[WPNewsPreheatTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"123"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        [cell setModelWithModel:_tradeArr[indexPath.section]];
        return cell;
    }
    WPNewsDealingTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        cell = [[WPNewsDealingTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"1234"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryNone;
    [cell setModelWithModel:_tradeArr[indexPath.section]];
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
//设置每一行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 280*DHFlexibleHorizontalMutiplier();
}
//用户点击了某一行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        WPTradeListViewController * vc = [WPTradeListViewController new];
        vc.model = _tradeArr[indexPath.section];
        [self pushToNextController:vc withVCTitle:@"交易期"];
    }
    else if(indexPath.section < 3){
        WPTradeDetailViewController * detailVC = [WPTradeDetailViewController new];
        detailVC.imageName = _detailImageNames[indexPath.section];
        [self pushToNextController:detailVC withVCTitle:@"项目详情"];
    }
}
#pragma mark -getter
- (UISegmentedControl *)segmentControl {
    if (!_segmentControl) {
        _segmentControl = ({
            UISegmentedControl * seg = [[UISegmentedControl alloc]initWithItems:@[@"票务", @"产品"]];
            seg.bounds = CGRectMake(0, 0, 130*DHFlexibleHorizontalMutiplier(), 24*DHFlexibleHorizontalMutiplier());
            seg.center = CGPointMake(self.view.center.x, navBar_height/2.0);
            seg.selectedSegmentIndex = 0;
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:12.0f*DHFlexibleHorizontalMutiplier()],NSFontAttributeName ,nil];
            [seg setTitleTextAttributes:dic forState:UIControlStateNormal];
            [seg addTarget:self action:@selector(respondsToSegment:) forControlEvents:UIControlEventValueChanged];
            seg;
        });
    }
    return _segmentControl;
}
- (UIScrollView *)backScrollView {
    if (!_backScrollView) {
        _backScrollView = ({
            UIScrollView * view = [[UIScrollView alloc]initWithFrame:CGRectMake(0, navBar_Fheight, SCREEN_SIZE.width, SCREEN_SIZE.height - navBar_Fheight)];
            view.contentSize = CGSizeMake(2*SCREEN_SIZE.width, 0);
            view.showsVerticalScrollIndicator = NO;
            view.showsHorizontalScrollIndicator = NO;
            view.pagingEnabled = YES;
            view.bounces = NO;
            view.delegate = self;
            view;
        });
    }
    return _backScrollView;
}
- (UIView *)footView {
    if (!_footView) {
        _footView = ({
            UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_SIZE.width, 70*DHFlexibleHorizontalMutiplier())];
            UILabel * lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 20*DHFlexibleHorizontalMutiplier(), SCREEN_SIZE.width, 30*DHFlexibleHorizontalMutiplier())];
            lab.textAlignment = NSTextAlignmentCenter;
            lab.textColor = COLOR_RGB(141, 141, 141, 1);
            lab.font = [UIFont systemFontOfSize:12*DHFlexibleHorizontalMutiplier()];
            lab.text = @"没有更多数据";
            [view addSubview:lab];
            view;
        });
    }
    return _footView;
}
- (UITableView *)tradeTableView {
    if (!_tradeTableView) {
        _tradeTableView = ({
            UITableView * tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 5*DHFlexibleHorizontalMutiplier(), SCREEN_SIZE.width, SCREEN_SIZE.height - navBar_Fheight - 5*DHFlexibleHorizontalMutiplier()) style:UITableViewStylePlain];
            tableview.dataSource = self;
            tableview.delegate = self;
            tableview.tableFooterView = [UIView new];
            tableview.pagingEnabled = NO;
            tableview.separatorColor = [UIColor clearColor];
            tableview;
        });
    }
    return _tradeTableView;
}
- (UILabel *)noMoreLabel {
    if (!_noMoreLabel) {
        _noMoreLabel = ({
            UILabel * lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_SIZE.width, 30*DHFlexibleHorizontalMutiplier())];
            lab.center = self.view.center;
            lab.font = [UIFont systemFontOfSize:12*DHFlexibleHorizontalMutiplier()];
            lab.textAlignment = NSTextAlignmentCenter;
            lab.text = @"暂无数据";
            lab;
        });
    }
    return _noMoreLabel;
}
- (UIView *)rightView {
    if (!_rightView) {
        _rightView = ({
            UIView * view = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_SIZE.width, 0, SCREEN_SIZE.width, SCREEN_SIZE.height-navBar_Fheight)];
            UILabel * lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_SIZE.width, 30*DHFlexibleHorizontalMutiplier())];
            lab.center = CGPointMake(SCREEN_SIZE.width/2.0, self.view.center.y);
            lab.font = [UIFont systemFontOfSize:12*DHFlexibleHorizontalMutiplier()];
            lab.textAlignment = NSTextAlignmentCenter;
            lab.text = @"暂无更多项目了~敬请期待吧";
            lab.textColor = [UIColor blackColor];
            [view addSubview:lab];
            view;
        });
    }
    return _rightView;
}
@end
